<template>
  <div>
    <headNav  :isHome="isHome" :signIn="!isHome" :isBack="isHome" ></headNav>
  
    <div class="flexHeight" style="align-items: center;" >
      <div class="flexCenter inputDiv" >
        <span>教师姓名：</span>
        <input type="text" v-model="name" :disabled="disabledName"  maxlength="10" />
      </div>
<!-- 
      <div class="inputDiv" style="width: 100%; margin-top: 0.3rem;" v-if="!codeNum && preselectionList.length > 0" >
        <span style="margin-left: 0.4rem;" >推荐加入班级:</span>
      </div>

      <div class="choiceDiv" v-if="!codeNum" >
        <div class="flexHeight" :class="{'borderCss': borderNum == val.qrCode }" v-for="(val, index) in preselectionList" :key="index" @click="borderNumClick(val)" >
          <span>{{val.gradeName}}{{val.name}}</span>
          <span class="choiceSpan" >{{inviteUserTeacher.InviteUserTeacherName}}</span>
          <img src="@/assets/img/my/blueHook.png" mode="" v-if="val.qrCode == borderNum" >
        </div>
      </div>
      <div class="youTitle" v-if="!borderNum" >
        <span style="margin-left: 0.4rem;" >您也可以通过班级号加入</span>
      </div>
       -->
      <div class="flexCenter inputDiv">
        <span>班级号：</span>
        <input type="text" v-model="codeNum" style="width: 4rem;"  maxlength="10" />
        <img src="@/assets/img/my/code.png" mode="" @click="sweepClick" >
      </div>
      <!-- <div class="flexCenter inputDiv choiceCss" v-if="!borderNum" >
        <span>学科：</span>
        <div @click="subjectClick" style="color: #bbb6b6;" v-if="subjectList.length == 0" >请先填写班级号</div>
        <div @click="subjectClick" v-else class="symbol" >
          <span v-for="(val, index) in subjectVal" :key="inedx" >{{val.name}}&#8194;</span>
        </div>
      </div> -->
      <button type="default" @click="joinClick" >加入班级</button>
      <button type="default" @click="$router.push('establish')" class="classButton" >创建班级</button>

     
    </div>
    <!-- 选择学科按钮弹窗 -->
    <x-dialog v-model="showHideOnBlurs" class="dialog-demo" hide-on-blur>
     <div>
      <div class="establishCss" >
        <span style="font-size: 0.35rem; font-weight: 600;" >勾选学科</span>
        <checklist title="" :options="subjectList" v-model="checklistVal" @on-change="subjectChange"  ></checklist>
      </div>
     </div>
    </x-dialog>
  </div>
</template>

<script>
import headNav from '@/components/headNav/headNav.vue'
import { mapActions, mapState, mapGetters, mapMutations } from 'vuex'
import { postExistenceClassApi, getSuperiorApi, getTeachingApi, getTeacherInfoApi, getTeacherApi, getClassNumberApi } from '@/api/myNewApi'
import cookie from '@/util/cookie'
import {refreshToken} from '@/api/commonApi'
import {XDialog, Checklist} from 'vux'
export default {
  components: {
    headNav,
    XDialog,
    Checklist
  },
  computed: {
    ...mapState({
      studentId: state => state.user.studentId,
      roleCode: state => state.user.roleCode,
      teacherId: state => state.user.teacherId
    })
  },
  data () {
    return {
      borderNum: '',
      name: '',
      codeNum: '',
      subjectVal: [],   // 用户选择的学科
      checklistVal: [],
      showHideOnBlurs: false,
      preselectionList: [],
      isHome: true,
     
    
      disabledName: false,
      subjectList: [],   // 存放学科数组
    
    }
  },
  methods: {
    // 勾选过程中触发的事件
    subjectChange () {
      // console.log(111111)
    },
    // 选择学科触发事件
    subjectClick () {
      if (!this.codeNum) {
        this.$vux.toast.text('请先填写班级号', 'middle')
        return
      }

      this.showHideOnBlurs = true
    },
    // 点击选择的班级触发的事件
    borderNumClick (e) {
      if (this.borderNum == e.qrCode) {
        this.borderNum = ''
      } else {
        this.borderNum = e.qrCode
      }

    },
   
    getParams(url) {
     
        url = url.substring(url.indexOf('?'))
     
        url = url.substring(0, url.indexOf('#'))
    
        var search = url.replace('?', '')
      
        var arr = search.split('&')
        var obj = {}
        for (var item of arr) {
            var list = item.split('=')
            obj[list[0]] = list[1]
        }
    
        return obj
    },
    // 点击扫码图片触发事件
    sweepClick () {
      let _this = this
      wx.scanQRCode({
        needResult: 1,   // 默认为0，扫描结果由微信处理。 1则直接返回扫描结果
        scanType: ["qrCode", "barCode"],  // 可以指定扫二维码还是一维码
        async success(res) {
        
          try {
            
             
              let qrcode = _this.getParams(res.resultStr).qrcode
             
              if (!qrcode) {
                _this.$vux.toast.text('未识别到班级码', 'middle')
                
              }
              _this.packQRCode(qrcode)
          } catch (error) {
          
          }
          

          // let arr = ''
          // if (res.resultStr.indexOf('=') != -1 && res.resultStr.indexOf('#') != -1) {
          //   let arr1 = res.resultStr.split('=')  // ?a=1&b=2
          //   let arr2 = arr1[1].split('#')
          //   arr = arr2[0]
          // } else {
          //   arr = res.resultStr
          // }
          // this.packQRCode(arr)

        }
      })
    },
    // 点击加入班级触发事件
    async joinClick () {
      this.name = this.name.replace(/\s*/g,"")
      this.codeNum = this.codeNum.replace(/\s*/g,"")

      if (!this.name) {
        this.$vux.toast.text('请填写教师姓名', 'middle')
        return
      }

      if (this.name.length > 6) {
        this.$vux.toast.text('教师姓名过长，请重新输入', 'middle')
        return
      }

      if (!this.borderNum && !this.codeNum) {
        this.$vux.toast.text('请选择或填写需要加入的班级', 'middle')
        return
      }

      if (this.codeNum.length > 7) {
        this.$vux.toast.text('班级号长度过长，请确认', 'middle')
        return
      }

      // if (this.checklistVal.length == 0) {
      //   this.$vux.toast.text('请选择关联学科', 'middle')
      //   return
      // }


      this.$vux.confirm.show({
          title: '提示',
          content: '是否确定加入班级？',
          onConfirm : async () => {
            let params = {
              teacherName: this.name,
              classQRCode: this.codeNum
            }
            if (!this.codeNum) {
              params.classQRCode = this.borderNum
            }
            let res = await postExistenceClassApi(params)
            console.log(res)
            this.$vux.toast.text('加入成功', 'middle')
             this.$store.state.user.reloadToken = true
             await this.$store.dispatch('user/refreshAccessToken')
            await this.$store.dispatch('user/getTeacherByLoginUserId')
         
            this.$router.push('myClassClass')
          },
          onCancel () {
          }
      })
    },

    //  根据班级码查询班级封装
    async packQRCode (code) {
      let params = {
        qrCode: code
      }
      let val = await getClassNumberApi(params)
      if (!val) {
        this.$vux.toast.text('识别的班级码不存在', 'middle')
        this.codeNum = ''
      } else {
        this.codeNum = code
      }
    }
  },
  async mounted() {
   localStorage.removeItem('role')
    
    // if (!localStorage.getItem("role") || localStorage.getItem("role") == undefined) {
    if (this.roleCode){
      this.isHome = true
   
    
      this.disabledName = true
      let user = await getTeacherInfoApi(cookie.get('teacherId'))
      this.name = user.name
      
    } else {
      
      // ——————————————————————————————————————————————————————————
      // var search = location.search
      // search = search.split('?')
      // var arr = search[1].split('&')
      // var obj = {}
      // for (var item of arr) {
      //     var list = item.split('=')
      //     obj[list[0]] = list[1]
      // }
      // this.packQRCode(localStorage.localQRCode)
      // ——————————————————————————————————————————————————————————
      
      
      
      if (!localStorage.localQRCode || localStorage.localQRCode == undefined) {
        this.codeNum = ''
      } else {
        this.packQRCode(localStorage.localQRCode)
         localStorage.removeItem('localQRCode')
      }
      

      this.isHome = false
  
   
      try {
        let teacher = await getTeacherApi()
        this.name = teacher.name
        this.disabledName = true
        
      }
      catch (e) {
        this.name = ''
        this.disabledName = false
        
      }

    }


    // try {
    //   let res = await getSuperiorApi()
    //   this.inviteUserTeacher = res
    //   this.preselectionList = []
   
    //   if (res.inviteUserTeacherId) {
    //     let val = await getTeachingApi(res.inviteUserTeacherId)
    //     for (let i of val) {
    //       for (let j of i.classes) {
    //         this.preselectionList.push(j)
    //       }
    //     }
    //   }
    // }
    // catch(e) {
    //   this.preselectionList = []
    //   console.log(e)
    //   console.log('尼玛的')
    // }

  }
}
</script>

<style lang="less" scoped >
.choiceCss {
  position: relative;
  margin-left: -0.4rem;
  .symbol {
    display: flex;
    flex-wrap: wrap;
    padding: 0.1rem 0.2rem;
    overflow-y: auto;
  }
  div {
    width: 4.25rem;
    height: 0.85rem;
    border: 0;
    border-radius: 0.2rem;
    padding-left: 0.3rem;
    font-size: 0.28rem;
    background: #FFF;
    display: flex;
    align-items: center;
  }
}

  .classButton {
    background: #FFF;
    border: 1px solid #128EFE;
    color: #128EFE;
    margin: 0;
  }

  .borderCss {
    border: 2px solid #128FEF!important;
  }

  .youTitle {
    width: 100%;
    font-size: 0.24rem;
    margin-top: 0.3rem;
  }

  .choiceDiv {
    display: flex;
    align-items: center;
    justify-content: space-around;
    flex-wrap: wrap;
    width: 100%;
    .choiceSpan {
      font-size: 0.24rem;
      color: #777777;
      margin-top: 0.15rem;
    }
    div {
      width: 3rem;
      height: 1.5rem;
      border: 2px solid #EEE;
      border-radius: 0.15rem;
      background: #FFF;
      font-size: 0.28rem;
      margin-top: 0.2rem;
      justify-content: center;
      align-items: center;
      position: relative;
    }
    img {
      position: absolute;
      top: 0;
      right: 0;
      width: 0.56rem;
      height: 0.56rem;
    }
  }

  button {
    width: 5.6rem;
    height: 0.84rem;
    background: #128FEF;
    color: #FFF;
    border-radius: 0.42rem;
    font-size: 0.32rem;
    border: 0;
    margin: 0.7rem 0 0.4rem 0;
  }

.inputDiv {
  font-size: 0.28rem;
  margin-top: 0.4rem;
  input {
    width: 4.7rem;
    height: 0.85rem;
    border: 0;
    border-radius: 0.2rem;
    padding-left: 0.3rem;
    font-size: 0.28rem;
  }
  img {
    width: 0.5rem;
    margin-left: 0.3rem;
  }
}

.flexCenter {
  display: flex;
  align-items: center;
  justify-content: center;
}

.flexHeight {
  display: flex;
  flex-direction: column;
}

.flexAlign {
  display: flex;
  align-items: center;
}

.flexEdge {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
